package xml;

import org.dom4j.Attribute;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.io.File;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

/**
 * @author 孙许
 * @date 2018-04-20
 * @description
 */
public class ReadxmlByDom4j {

    private List<Book> books;
    private Book book;
    private SAXReader reader;

    public List<Book> getBooks(File file) throws DocumentException {
        reader = new SAXReader();
        Document doc = reader.read(file);
        Element bookStore = doc.getRootElement();
        Iterator storeIt = bookStore.elementIterator();

        books = new ArrayList<>();
        while (storeIt.hasNext()) {
            book = new Book();
            Element bookElement = (Element) storeIt.next();
            //遍历bookElement的属性
            List<Attribute> attributes = bookElement.attributes();
            for (Attribute attribute : attributes) {
                if (attribute.getName().equals("id")) {
                    String id = attribute.getValue();
                    book.setId(Integer.parseInt(id));
                }
            }

            Iterator bookIt = bookElement.elementIterator();
            while (bookIt.hasNext()) {
                Element child = (Element) bookIt.next();
                String nodeName = child.getName();
                if (nodeName.equals("name")) {
                    //System.out.println(child.getStringValue());
                    String name = child.getStringValue();
                    book.setName(name);
                } else if (nodeName.equals("author")) {
                    String author = child.getStringValue();
                    book.setAuthor(author);
                } else if (nodeName.equals("year")) {
                    String year = child.getStringValue();
                    book.setYear(Integer.parseInt(year));
                } else if (nodeName.equals("price")) {
                    String price = child.getStringValue();
                    book.setPrice(Double.parseDouble(price));
                }
            }
            books.add(book);
            book = null;
        }

        return books;
    }
}
